//import store from "@/store";
//import {useStore} from "@gd-accbuild-core/store/hackVueStore"
//import permissionStore from "../../store/modules/permission"
//import historyRouteStore from "../../store/modules/historyRoute"

//const permissionStore = null
//const historyRouteStore = null
import {
  resourceApiAliasConfig,
  globalConfig,
} from "@gd-accbuild-core/config";

import { hackFixPageNotFound } from "../hackFixPageNotFound";
const { resourceTypeKeyAlias } = resourceApiAliasConfig;
export const createRouter = ({
  constantRoutes = [],
  constantResources = [],
}) => {
  routerInstance.constantRoutes = constantRoutes;
  routerInstance.constantResources = constantResources;
  return routerInstance;
};

export const useRouter = () => {
  return routerInstance;
};

const routerNext = (val = true) => {
  if (typeof val === "boolean") {
    return {
      isNext: val,
    };
  } else if (
    typeof val === "object" &&
    Object.keys(val).some((key) => ["path", "url"].includes(key))
  ) {
    return {
      isNext: true,
      ...val,
    };
  } else {
    return {
      isNext: false,
    };
  }
};

/**
 * 根据key 获取地址栏query的value
 */
export function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  let searchStr = "";
  if (window.location.search) {
    searchStr = window.location.search.substring(1);
  } else {
    if (globalConfig.ROUTER_MODE === "hash") {
      const flagIdx = window.location.hash.indexOf("?");
      if (flagIdx !== -1) {
        searchStr = window.location.hash.substring(flagIdx + 1);
      }
    }
  }
  var r = searchStr.match(reg);
  if (r != null) return decodeURIComponent(decodeURIComponent(r[2]));
  return null;
}

/**
 * @typedef {Object} RouterInfo
 * @property {string} url - /pages/···开头
 * @property {string} path - path
 * @property {Object} query - query
 * @property {string} queryStr - queryStr
 */
/**
 * @description: 获取路由信息
 * @param {Object} config
 * @param {string} config.url 要跳转的链接，可带参数;注: 这里的url  可以包括 globalConfig.BASE_ROUTER_PREFIX_PATH,但内部转换后为/pages/···开始
 * @param {String} config.path  /pages/··· 或 /uni_modules/··· 开始的部分
 * @param {Object} config.query 查询参数
 * @return {RouterInfo} RouterInfo
 */
export const getRouterInfo = (
  { url = "", path: localpath, query = {} } = { url: "", path: "", query: {} }
) => {
  let path = localpath;
  let queryStr = "";
  const urlSplitArr = url.split("?");
  const pathnameAndHash = url ? urlSplitArr[0] : path;
  if (pathnameAndHash) {
    if (globalConfig.ROUTER_MODE === "hash") {
      path = pathnameAndHash.split("#")[1];
    } else if (globalConfig.ROUTER_MODE === "history") {
      if (pathnameAndHash.startsWith(globalConfig.BASE_ROUTER_PREFIX_PATH)) {
        path = pathnameAndHash.replace(
          globalConfig.BASE_ROUTER_PREFIX_PATH,
          ""
        );
      } else {
        path = pathnameAndHash;
      }
    }
    //url里面有queryStr
    queryStr = urlSplitArr.length === 2 ? urlSplitArr[1] : "";
  }
  // 把queryStr里的加到query里面
  //https://blog.csdn.net/weixin_45256913/article/details/119908573#:~:text=%E6%88%91%E4%BB%AC%E9%83%BD%E7%9F%A5%E9%81%93qs.stringify,%28%29%E4%BD%9C%E7%94%A8%E6%98%AF%E5%B0%86%E5%AF%B9%E8%B1%A1%E6%88%96%E8%80%85%E6%95%B0%E7%BB%84%E5%BA%8F%E5%88%97%E5%8C%96%E6%88%90URL%E7%9A%84%E6%A0%BC%E5%BC%8F%EF%BC%8C%E6%A0%BC%E5%BC%8F%E5%8C%96%E6%95%B0%E7%BB%84%E5%8F%82%E6%95%B0%E6%9C%89%E4%B8%89%E7%A7%8D%E6%96%B9%E6%B3%95%EF%BC%8C%E8%A6%81%E6%B7%BB%E5%8A%A0arrayFormat
  const queryStrExcludeKeys = [];
  queryStr &&
    queryStr.split("&").forEach((el) => {
      const [key, val] = el.split("=");
      queryStrExcludeKeys.push(key);
      const decodeVal = decodeURIComponent(val);
      if (key === "ids") {
        if (query.hasOwnProperty(key) && Array.isArray(query[key])) {
          query[key].push(decodeVal);
        } else {
          query[key] = [decodeVal];
        }
      } else {
        query[key] = decodeVal;
      }
    });
  // 把query里的加到queryStr里面，当然排除上面加过的
  const queryKeys = Object.keys(query);
  if (queryKeys.length > 0) {
    queryKeys.forEach((key) => {
      if (!queryStrExcludeKeys.includes(key)) {
        let prefixStr = "";
        if (queryStr) {
          prefixStr = "&";
        }
        queryStr += `${prefixStr}${key}=${encodeURIComponent(query[key])}`;
      }
    });
  }
  path = !path ? "/" : path;
  if (!url) {
    url = `${path}${queryStr ? `?${queryStr}` : ""}`;
  }
  return {
    url,
    path,
    query,
    queryStr,
  };
};
/*
 * @param {String} url 要跳转的链接，可带参数;注: 这里的url  可以包括 globalConfig.BASE_ROUTER_PREFIX_PATH,但内部转换后为/pages/···开始
 * @param {String} path  /pages/··· 或 /uni_modules/··· 开始的部分
 * @param {Object} query 查询参数
 * @param {Function} callback 回调方法，做些特殊的事情 */
/**
 * @typedef {Object} JumpParams
 * @property {string} url - 要跳转的链接，可带参数;注: 这里的url  可以包括 globalConfig.BASE_ROUTER_PREFIX_PATH,但内部转换后为/pages/···开始
 * @property {string} path - /pages/··· 或 /uni_modules/··· 开始的部分
 * @property {Object} query - 查询参数
 * @property {Function} callback 回调方法，做些特殊的事情
 * @property {boolean} isFirstLoadResource 是否首次加载资源
 */
/**
 * @description: 拦截超链接跳转，解决页面栈10层限制
 * @param {JumpParams} JumpParams
 * @return {void}
 */
export const jumpTo = ({
  url: localUrl = "",
  path: localPath,
  query: localQuery = {},
  callback,
  isFirstLoadResource = false,
}) => {
  if (!(localUrl || localPath)) {
    return;
  }
  const store = globalConfig.store;
  let { url, path, queryStr, query } = getRouterInfo({
    url: localUrl,
    path: localPath,
    query: localQuery,
  });
  // 获取页面注册信息,若注册则首页的url重写
  let curPageInfo = store.state.permission.pages.find(
    (page) => page.targetResourceUrl === path
  );
  if (path === "/") {
    curPageInfo = store.state.permission.pages.find(
      (page) => page.uiOptions.pageTypeFlag === "Home"
    );
  }
  url = `${curPageInfo?.targetResourceUrl ?? path}${
    queryStr ? "?" + queryStr : ""
  }`;
  if (!curPageInfo) {
    const templatePagePathPrefix =
      "/uni_modules/gd-accbuild-core/pages/cross-platform/default-crud-pages";
    if (!path.startsWith(templatePagePathPrefix)) {
      new globalConfig.GD_Log({ flag: "JumpTo", level: "warn" }).println(
        `页面${path}没有注册在资源中`
      );
    }
    /* javascript-obfuscator:disable */
    uni
      .navigateTo({
        url,
      })
      .then(() => {
        callback && callback();
        if (isFirstLoadResource) {
          setTimeout(function () {
            location.reload();
          }, 1000);
        }
      })
      .catch((err) => {
        console.log(err);
      });
    /* javascript-obfuscator:enable */
    return;
  }
  // 页面注册了,则维护store/historyRoute
  curPageInfo = curPageInfo || {};

  // 开始执行路由前置钩子
  const to = {
    url: url,
    path: path,
    query: query,
    queryStr: queryStr,
    realPageKey: curPageInfo.realPageKey,
  };
  const visitedRoute = store.state.historyRoute.visitedRoute;
  const visitedRouteLength = visitedRoute.length;
  const from =
    visitedRouteLength > 0 ? visitedRoute[visitedRouteLength - 1] : null;
  const beforeEachRes = globalConfig.router["beforeEach"]()(
    to,
    from,
    routerNext
  );
  if (!beforeEachRes.isNext) {
    return;
  } else {
    url = beforeEachRes?.url ?? url;
    path = beforeEachRes?.path ?? path;
    query = beforeEachRes?.query ?? query;
    queryStr = beforeEachRes?.queryStr ?? queryStr;
  }

  // 开始执行维护store/historyRoute
  const targetPlatform = globalConfig.targetPlatform;
  store.commit("historyRoute/ADD_ROUTE", {
    url: url,
    path: path,
    query: query,
    queryStr: queryStr,
    realPageKey: curPageInfo.realPageKey,
    title: curPageInfo.name,
    layoutStyle: curPageInfo?.resource?.uiOptions?.layoutStyle ?? "",
  });

  store.commit("permission/SET_CURPAGEINFO", curPageInfo);
  // 执行开始跳转
  const isMobile = targetPlatform === "mobile";
  /* pc后台管理项目;由于多标签缓存实现uniapp尚未支持router-view,不能使用(router-view + keep-alive);必须使用 (动态component + keep-alive) 模拟 */
  if (!isMobile) {
    if (curPageInfo.resource.uiOptions.target === "_blank") {
      new globalConfig.GD_Log({ flag: "JumpTo" }).println("新开页面");
      window.open(
        `${globalConfig.BASE_ROUTER_PREFIX_PATH}${
          globalConfig.ROUTER_MODE === "hash" ? "/#" : ""
        }${url}`,
        "_blank"
      );
      return;
    }
  }
  /* javascript-obfuscator:disable */
  const page = getCurrentPages();
  /* javascript-obfuscator:enable */
  const index = page.findIndex((item) => item.route === path);

  /* 移动端情况跳转tabbar */
  const tabBarUrls = store.state.permission.pages
    .filter((el) => el[resourceTypeKeyAlias] === "Menu")
    .map((el) => el.targetResourceUrl);
  /* 如果是Tab中的链接，直接跳转 */
  if (tabBarUrls.includes(path) && isMobile) {
    /* javascript-obfuscator:disable */
    uni
      .switchTab({
        url: path,
      })
      .then(() => {
        callback && callback();
      })
      .catch();
    /* javascript-obfuscator:enable */
    return;
  }

  /* ----------------- */

  /* 在页面栈中找到时 */
  if (index !== -1) {
    const step = page.length - 1 - index;
    if (step === 0) {
      /* javascript-obfuscator:disable */
      uni.redirectTo({
        url,
        success: () => {
          callback && callback();
        },
      });
      /* javascript-obfuscator:enable */
    } else {
      /* javascript-obfuscator:disable */
      uni.navigateBack({
        delta: step,
      });
      /* javascript-obfuscator:enable */
      callback && callback();
    }
    return;
  }
  /* javascript-obfuscator:disable */
  uni
    .navigateTo({
      url,
    })
    .then(() => {
      callback && callback();
    })
    .catch((err) => {
      const isPageNotFound =
        err.errMsg ===
        `navigateTo:fail page \`${curPageInfo.targetResourceUrl}\` is not found`;
      hackFixPageNotFound({
        store,
        curPageInfo,
        isJumpFromAddrInput: false,
      });
    });
  /* javascript-obfuscator:enable */
};

const routerInstance = {
  beforeEach: (routerCallback = (to, from, next) => next()) => {
    return routerCallback;
  },
  push: jumpTo,
  constantRoutes: [],
  constantResources: [],
};
